<?php

	class DesktopDomain extends Domain{
		
		protected $dbObj;
		
		function dbObj(){
			if(is_null($this->dbObj)){
				$this->dbObj = smroot()->initDomain($this->DOM_ID, $this->NAME);
				if(!$this->dbObj) httpE(500, "failed to initialise domain ".$this->DOM_ID);
				// Here we allow ini edits to overwrite the db obj (it'll get called back here on commit)
				$this->dbObj->name = $this->NAME;
			}
			return $this->dbObj;
		}
		
		function __get($k){
			return (isset($this->$k)) ? $this->$k : $this->dbObj()->$k; 
		}
		
		function __set($k, $v){
			return $this->dbObj()->$k = $v;
		}
		
		function will_permit($usr){
			return $this->dbObj()->will_permit($usr);
		}
		
		protected function set_constants(){
			$this->DESKTOP = SERVER_NAME;
			parent::set_constants();
			if(!is_dir(DOM_TEMPDIR)) mkdir(DOM_TEMPDIR, 0755);
			if(!is_dir(DOM_DESKDIR)) mkdir(DOM_DESKDIR, 0755);
			if(!is_dir(DOM_LOG_DIR)) mkdir(DOM_LOG_DIR, 0755);
			ini_set('error_log', DOM_LOG_DIR.'/'.date('Y-m-d@H').'h.log');
		}
		
		function run(){
			Desktop()->run();
			exit;
		}
			
		function has_linked_name($domain){
			$domfile = $this->dom_symlink($domain);
			return (is_link($domfile) && ($fp = readlink($domfile)) && (realpath($fp) == realpath($this->config_file())));
		}
		
		function dom_symlink($domain){
			return ETC_DIR."/dom/$domain";
		}
						
		// set_config accepts an smconf string
		// returns error string on failure or bool commit success
		function set_config($data){
			if(!sm_amiroot(true)) return "you ain't root!";
			$conf = new domini($this->config_file());
			$conf->set_content($data);
			if(smroot()->detect_domain_name_clash($conf->NAME, $this->DOM_ID)) return "name clash in database with $conf->NAME";
			return ($conf->error() || !$conf->write()) ? $conf->error() : $this->commit();
		}

		function commit(){
			if(!sm_amiroot(true)) return false;
			$conf = $this->get_config();
			$this->dbObj()->name = $conf->NAME;
			$this->dbObj()->dom_commit();
			$newnames = $this->names($conf);
			//error_log(print_r($this->ALIASES, 1));
			foreach($this->names() as $oldname){
				if(in_array($oldname, $newnames)) continue;
				$symlink = $this->dom_symlink($oldname);
				if(is_file($symlink)) unlink($symlink);
			}
			foreach($newnames as $name){
				if($this->has_linked_name($name)) continue;	
				$symlink = $this->dom_symlink($name);
				if(is_file($symlink)) unlink($symlink);
				symlink($this->config_file(), $symlink);
			}
			foreach($conf as $k=>$v) $this->$k = $this->parse_conf_constants($v);
			return true;
		}
		
		function Desk(){
			return ($f = $this->Fmgr()) ? $f->open('desk:/') : false;	
		}
		
	}


